package io.mft.commons.db.mapper.transaction.impl;

import java.sql.SQLException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.hutool.db.Session;
import io.mft.commons.db.mapper.transaction.MapperTransaction;
import io.mft.commons.db.mapper.transaction.MapperTransactionSessionHandler;

public class MapperTransactionImpl implements MapperTransaction,MapperTransactionSessionHandler{
	static Logger logger=LoggerFactory.getLogger(MapperTransactionImpl.class);
	private boolean auto=false;
	public boolean isAuto() {
		return auto;
	}
	private HashMap<String, Session> map=new HashMap<String, Session>();
	private HashMap<String, Boolean> switchOffOn=new HashMap<String, Boolean>();
	private boolean begin=false;
	private ThreadLocal<MapperTransaction> threadLocal;
	public MapperTransactionImpl(ThreadLocal<MapperTransaction> threadLocal) {
		this.threadLocal=threadLocal;
	}
	public boolean isBegin() {
		return begin;
	}
	
	public void setAuto(boolean auto) {
		this.auto = auto;
	}
	@Override
	public void attachSession(String datasourceId,Session session) {
		map.put(datasourceId, session);
	}
	@Override
	public void begin(String datasourceId) {
		if (begin&&!auto) {
			Session session=map.get(datasourceId);
			if (session!=null) {
				if (switchOffOn.get(datasourceId)==null||!switchOffOn.get(datasourceId)) {
					try {
						session.beginTransaction();
					} catch (SQLException e) {
						logger.error("", e);
					}
					switchOffOn.put(datasourceId, true);
				}
			}
		}
	}
	public void commit() {
		Set<String> collection=switchOffOn.keySet();
		for (String datasourceId : collection) {
			try {
				Session session=map.get(datasourceId);
				session.commit();
			} catch (Exception e) {
				logger.error("", e);
			}
		}
	}
	public void rollback() {
		Set<String> collection=switchOffOn.keySet();
		for (String datasourceId : collection) {
			try {
				Session session=map.get(datasourceId);
				session.rollback();
			} catch (Exception e) {
				logger.error("", e);
			}
		}
	}
	public void close() {
		Collection<Session> collection=map.values();
		for (Session session : collection) {
			try {
				session.close();
			} catch (Exception e) {
				logger.error("", e);
			}
		}
		threadLocal.remove();
	}

	@Override
	public void begin() {
		begin=true;
	}

	@Override
	public Session getSession(String datasourceId) {
		return map.get(datasourceId);
	}
}
